"""The base Controller API

Provides the BaseController class for subclassing, and other objects
utilized by Controllers.
"""
from pylons import c, cache, config, g, request, response, session
from pylons.controllers import WSGIController
from pylons.controllers.util import abort, etag_cache, redirect_to
from pylons.decorators import jsonify, validate
from pylons.i18n import _, ungettext, N_
from pylons.templating import render as mako_render

import mtp.lib.helpers as h
import mtp.model as model
from mtp.lib.permissions import needs_perm, has_perm

import logging
log = logging.getLogger(__name__)

def is_ajax():
    return request.headers.get('X-Requested-With') == 'XMLHttpRequest'

def render(template):
    routes_dict = request.environ['pylons.routes_dict']
    controller = routes_dict['controller']
    action = routes_dict['action']

    nav_items = config['mtp.nav_items'][:]
    new_nav_items = []
    for na in nav_items:
        if na.permission and not has_perm(*na.permission):
            continue
        new_nav_items.append(na)
    c.nav_items = new_nav_items

    page_actions = config['mtp.page_actions'][None][:]
    page_actions.extend(c.page_actions)
    if config['mtp.page_actions'].has_key((controller, action)):
        for data in config['mtp.page_actions'][(controller, action)]:
            if callable(data):
                data = data()
            page_actions.extend(data)

    new_page_actions = []
    for pa in page_actions:
        if pa.permission and not has_perm(*pa.permission):
            continue
        new_page_actions.append(pa)

    c.page_actions = new_page_actions

    def getcontent(items):
        ret = []
        if items.has_key((controller, action)):
            for data in items[(controller, action)]:
                if callable(data):
                    data = data()
                if data:
                    ret.append(data)
        return ret

    c.content_head    = getcontent(config['mtp.content.head'])
    c.content_prepend = getcontent(config['mtp.content.prepend'])
    c.content_append  = getcontent(config['mtp.content.append'])

    return mako_render(template)


class BaseController(WSGIController):

    def __before__(self, controller, action):
        c.config = config
        c.user = session.get('user')
        c.page_actions = []

    def __call__(self, environ, start_response):
        """Invoke the Controller"""
        # WSGIController.__call__ dispatches to the Controller method
        # the request is routed to. This routing information is
        # available in environ['pylons.routes_dict']
        try:
            return WSGIController.__call__(self, environ, start_response)
        finally:
            model.Session.remove()

# Include the '_' function in the public names
__all__ = [__name for __name in locals().keys() if not __name.startswith('_') \
           or __name == '_']



